// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>

#include <nebula/core/buffer.h>
#include <nebula/core/memory_pool.h>

#include <nebula/types/type_fwd.h>
#include <nebula/bits/bit_util.h>
#include <turbo/meta/compare.h>
#include <turbo/functional/functional.h>
#include <turbo/base/macros.h>
#include <turbo/strings/string_builder.h>
#include <nebula/util/type_traits.h>
#include <turbo/base/macros.h>

namespace nebula::internal {

    /// \brief Store a stack of bitsets efficiently. The top bitset may be
    /// accessed and its bits may be modified, but it may not be resized.
    class BitsetStack {
    public:
        using reference = typename std::vector<bool>::reference;

        /// \brief push a bitset onto the stack
        /// \param size number of bits in the next bitset
        /// \param value initial value for bits in the pushed bitset
        void Push(int size, bool value) {
            offsets_.push_back(bit_count());
            bits_.resize(bit_count() + size, value);
        }

        /// \brief number of bits in the bitset at the top of the stack
        int TopSize() const {
            if (offsets_.size() == 0) return 0;
            return bit_count() - offsets_.back();
        }

        /// \brief pop a bitset off the stack
        void Pop() {
            bits_.resize(offsets_.back());
            offsets_.pop_back();
        }

        /// \brief get the value of a bit in the top bitset
        /// \param i index of the bit to access
        bool operator[](int i) const { return bits_[offsets_.back() + i]; }

        /// \brief get a mutable reference to a bit in the top bitset
        /// \param i index of the bit to access
        reference operator[](int i) { return bits_[offsets_.back() + i]; }

    private:
        int bit_count() const { return static_cast<int>(bits_.size()); }

        std::vector<bool> bits_;
        std::vector<int> offsets_;
    };

}  // namespace nebula::internal
